package code.whmmm.util.spring.util;

/**
 * <p><b>
 *
 * </b></p>
 * <br/>
 * 创建时间: 8/14/2019 1:21 PM
 *
 * @author Zero
 */

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 从 spring 容器中，获取 bean
 *
 * @author Zero
 */
@Component
public class SpringBeanUtil implements ApplicationContextAware {

    private SpringBeanUtil() {
    }

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContextParam)
            throws BeansException {
        applicationContext = applicationContextParam;
    }

    public static Object getObject(String id) {
        Object object = null;
        object = applicationContext.getBean(id);
        return object;
    }

    public static <T> T getObject(Class<T> tClass) {
        return applicationContext.getBean(tClass);
    }

    public static Object getBean(String tClass) {
        return applicationContext.getBean(tClass);
    }

    /**
     * @param clazz    类字节码
     * @param beanName bean 的名称
     * @param <T>      类型
     * @return bean
     */
    public static <T> T getBean(Class<T> clazz, String beanName) {
        return applicationContext.getBean(beanName, clazz);
    }

    public static <T> T getBean(Class<T> tClass) {
        return applicationContext.getBean(tClass);
    }

    /**
     * 获取 bean 的 实现类。
     *
     * @param t   类.class
     * @param <T> 类型
     * @return Map
     */
    public <T> Map<String, T> getBeansByType(Class<T> t) {
        return applicationContext.getBeansOfType(t);
    }
}
